import React, { useState, useEffect, useMemo, useRef } from "react";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { toast } from "@/components/ui/use-toast";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import {
  Pilcrow,
  Edit,
  Trash2,
  Plus,
  Upload,
  MoreHorizontal,
  ChevronLeft,
  ChevronRight,
  X,
  FileText,
  AlertCircle,
  CheckCircle2,
} from "lucide-react";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import PronJectModal from "./PronJectModal";

// 杆塔类型映射
const towerTypeLabels = {
  tensionTower: "耐张塔",
  straightLineTower: "直线塔",
  angleTower: "转角塔",
  branchTower: "分支塔",
};

const typeColors = {
  tensionTower: "bg-purple-100 text-purple-800 border-purple-200",
  straightLineTower: "bg-green-100 text-green-800 border-green-200",
  angleTower: "bg-orange-100 text-orange-800 border-orange-200",
  branchTower: "bg-blue-100 text-blue-800 border-blue-200",
};

// 数值格式化函数 - 限制最多两位小数
const formatNumber = (value) => {
  if (value === null || value === undefined || value === "") return "-";
  
  const num = parseFloat(value);
  if (isNaN(num)) return value;
  
  // 如果是整数，不显示小数部分
  if (Number.isInteger(num)) {
    return num.toString();
  }
  
  // 限制最多两位小数，去掉末尾的0
  return parseFloat(num.toFixed(2)).toString();
};

// 数值输入处理函数
const handleNumberInput = (value, setValue, maxDecimals = 2) => {
  // 允许空值
  if (value === "") {
    setValue("");
    return;
  }
  
  // 只允许数字和小数点
  const cleanedValue = value.replace(/[^\d.]/g, '');
  
  // 防止多个小数点
  const parts = cleanedValue.split('.');
  if (parts.length > 2) {
    // 如果有多个小数点，只保留第一个
    setValue(parts[0] + '.' + parts.slice(1).join(''));
    return;
  }
  
  // 限制小数位数
  if (parts.length === 2 && parts[1].length > maxDecimals) {
    setValue(parts[0] + '.' + parts[1].slice(0, maxDecimals));
    return;
  }
  
  setValue(cleanedValue);
};

// 数值输入组件
const NumberInput = ({ value, onChange, placeholder, min, max, step = "0.01", ...props }) => {
  const [displayValue, setDisplayValue] = useState(value);
  
  useEffect(() => {
    setDisplayValue(value);
  }, [value]);
  
  const handleChange = (e) => {
    const inputValue = e.target.value;
    handleNumberInput(inputValue, setDisplayValue);
  };
  
  const handleBlur = (e) => {
    const numValue = parseFloat(displayValue);
    
    if (displayValue === "" || isNaN(numValue)) {
      // 空值或无效数字，恢复原值或设为空
      setDisplayValue(value || "");
      onChange(value || "");
      return;
    }
    
    // 应用范围限制
    let finalValue = numValue;
    if (min !== undefined && numValue < min) {
      finalValue = min;
    }
    if (max !== undefined && numValue > max) {
      finalValue = max;
    }
    
    // 限制小数位数
    finalValue = parseFloat(finalValue.toFixed(2));
    
    setDisplayValue(finalValue.toString());
    onChange(finalValue);
  };
  
  return (
    <Input
      type="text"
      value={displayValue}
      onChange={handleChange}
      onBlur={handleBlur}
      placeholder={placeholder}
      {...props}
    />
  );
};

export default function ProjectTowersList({
  project,
  towers,
  onEdit,
  onDelete,
  onAddNew,
  onRefresh,
  onImport,
}) {
  const [currentPage, setCurrentPage] = useState(1);
  const [itemsPerPage, setItemsPerPage] = useState(10);
  const [paginatedTowers, setPaginatedTowers] = useState([]);
  const [totalItems, setTotalItems] = useState(0);

  const [isImportModalOpen, setIsImportModalOpen] = useState(false);
  const [selectedFile, setSelectedFile] = useState(null);
  const [parsedData, setParsedData] = useState([]);
  const [importErrors, setImportErrors] = useState([]);
  const [importProgress, setImportProgress] = useState(0);
  const [importStatus, setImportStatus] = useState(null);
  const fileInputRef = useRef(null);

  // 缓存筛选结果
  const projectTowers = useMemo(() => {
    return towers?.filter((t) => t.projectId === project?.id) || [];
  }, [towers, project?.id]);

  // 计算总页数
  const totalPages = useMemo(() => {
    return Math.ceil(totalItems / itemsPerPage) || 1;
  }, [totalItems, itemsPerPage]);

  // 更新分页数据
  useEffect(() => {
    const newTotal = projectTowers.length;
    setTotalItems(newTotal);
    
    if (currentPage > totalPages) {
      setCurrentPage(totalPages);
    }
  }, [projectTowers, itemsPerPage, currentPage, totalPages]);

  // 分页数据计算
  useEffect(() => {
    const startIndex = (currentPage - 1) * itemsPerPage;
    const endIndex = startIndex + itemsPerPage;
    setPaginatedTowers(projectTowers.slice(startIndex, endIndex));
  }, [currentPage, itemsPerPage, projectTowers]);

  // 页码切换逻辑
  const handlePageChange = (pageNum) => {
    if (pageNum < 1 || pageNum > totalPages) return;
    setCurrentPage(pageNum);
    document.querySelector('.overflow-x-auto')?.scrollTo(0, 0);
  };

  const handleItemsPerPageChange = (count) => {
    setItemsPerPage(count);
    setCurrentPage(1);
  };

  // 导入成功
  const handleImportSuccess = () => {
    setIsImportModalOpen(false);
    setCurrentPage(1);
    onRefresh && onRefresh();
    toast({ title: "成功", description: "杆塔数据批量导入完成" });
  };

  // 重置导入状态
  const resetImportState = () => {
    setSelectedFile(null);
    setParsedData([]);
    setImportErrors([]);
    setImportProgress(0);
    setImportStatus(null);
    if (fileInputRef.current) {
      fileInputRef.current.value = "";
    }
  };

  // 处理杆塔编号点击编辑
  const handleTowerNumberClick = (tower) => {
    if (onEdit) {
      onEdit(tower);
    }
  };

  // 分页组件渲染
  const renderPagination = () => {
    const getPageNumbers = () => {
      const pages = [];
      const maxVisiblePages = 5;

      if (totalPages <= maxVisiblePages) {
        for (let i = 1; i <= totalPages; i++) {
          pages.push(i);
        }
      } else {
        const startPage = Math.max(1, currentPage - 2);
        const endPage = Math.min(totalPages, currentPage + 2);

        if (startPage > 1) {
          pages.push(1);
          if (startPage > 2) {
            pages.push(null);
          }
        }

        for (let i = startPage; i <= endPage; i++) {
          pages.push(i);
        }

        if (endPage < totalPages) {
          if (endPage < totalPages - 1) {
            pages.push(null);
          }
          pages.push(totalPages);
        }
      }

      return pages;
    };

    const pageNumbers = getPageNumbers();

    return (
      <div className="flex flex-col sm:flex-row items-center justify-between gap-4 px-4 py-3 border-t">
        <div className="text-sm text-gray-500">
          共 {totalItems} 条数据，显示
          {(currentPage - 1) * itemsPerPage + 1} 到
          {Math.min(currentPage * itemsPerPage, totalItems)} 条
        </div>
        <div className="flex items-center gap-2">
          <DropdownMenu>
            <DropdownMenuTrigger asChild>
              <Button variant="outline" size="sm" className="h-8">
                每页 {itemsPerPage} 条
                <MoreHorizontal className="ml-2 h-4 w-4" />
              </Button>
            </DropdownMenuTrigger>
            <DropdownMenuContent align="end">
              {[5, 10, 20, 50].map((count) => (
                <DropdownMenuItem
                  key={count}
                  onClick={() => handleItemsPerPageChange(count)}
                >
                  {count} 条/页
                </DropdownMenuItem>
              ))}
            </DropdownMenuContent>
          </DropdownMenu>
          <div className="flex items-center gap-1">
            <Button
              variant="outline"
              size="icon"
              className="h-8 w-8"
              onClick={() => handlePageChange(currentPage - 1)}
              disabled={currentPage === 1}
              aria-label="上一页"
            >
              <ChevronLeft className="h-4 w-4" />
            </Button>

            {pageNumbers.map((pageNum, index) => (
              pageNum === null ? (
                <span key={`ellipsis-${index}`} className="flex items-center justify-center h-8 w-8 text-gray-400">
                  ...
                </span>
              ) : (
                <Button
                  key={pageNum}
                  variant={currentPage === pageNum ? "default" : "outline"}
                  size="icon"
                  className="h-8 w-8"
                  onClick={() => handlePageChange(pageNum)}
                  aria-label={`第 ${pageNum} 页`}
                >
                  {pageNum}
                </Button>
              )
            ))}

            <Button
              variant="outline"
              size="icon"
              className="h-8 w-8"
              onClick={() => handlePageChange(currentPage + 1)}
              disabled={currentPage === totalPages}
              aria-label="下一页"
            >
              <ChevronRight className="h-4 w-4" />
            </Button>
          </div>
        </div>
      </div>
    );
  };

  if (!project || !towers) return null;

  return (
    <>
      <Card className="mt-8 shadow-lg border-0">
        <CardHeader className="bg-gradient-to-r from-purple-50 to-pink-50 border-b">
          <div className="flex items-center justify-between">
            <CardTitle className="text-xl font-bold text-gray-800 flex items-center gap-2">
              <Pilcrow className="w-6 h-6 text-purple-600" />
              杆塔列表
            </CardTitle>
            <div className="flex items-center gap-2">
              <Button onClick={onAddNew} variant="outline">
                <Plus className="w-4 h-4 mr-2" />
                新增杆塔
              </Button>
              <Button onClick={() => setIsImportModalOpen(true)}>
                <Upload className="w-4 h-4 mr-2" />
                批量导入
              </Button>
            </div>
          </div>
        </CardHeader>

        <CardContent className="p-6 pt-0">
          {projectTowers.length > 0 ? (
            <>
              <div className="overflow-x-auto pt-6">
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead>杆塔编号</TableHead>
                      <TableHead>类型</TableHead>
                      <TableHead>高度(m)</TableHead>
                      <TableHead>呼称高(m)</TableHead>
                      <TableHead>到下一塔档距(m)</TableHead>
                      <TableHead>坐标</TableHead>
                      <TableHead className="text-right">操作</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {paginatedTowers.map((tower) => (
                      <TableRow key={tower.id} className="hover:bg-gray-50">
                        <TableCell className="font-medium">
                          <div 
                            className="font-medium hover:text-blue-600 hover:underline cursor-pointer transition-colors"
                            onClick={() => handleTowerNumberClick(tower)}
                          >
                            {tower.towerNumber}
                          </div>
                        </TableCell>
                        <TableCell>
                          <Badge className={`${typeColors[tower.type]} border`}>
                            {towerTypeLabels[tower.type]}
                          </Badge>
                        </TableCell>
                        <TableCell>
                          {formatNumber(tower.height)}
                        </TableCell>
                        <TableCell>
                          {formatNumber(tower.groundElevation)}
                        </TableCell>
                        <TableCell>
                          {tower.spanToNextTower ? (
                            <span className="font-medium text-blue-600">
                              {formatNumber(tower.spanToNextTower)}
                            </span>
                          ) : (
                            <span className="text-gray-400">-</span>
                          )}
                        </TableCell>
                        <TableCell className="text-sm text-gray-500">
                          {tower.latitude && tower.longitude ? (
                            <>
                              {formatNumber(tower.latitude)}, {formatNumber(tower.longitude)}
                            </>
                          ) : (
                            "-"
                          )}
                        </TableCell>
                        <TableCell className="text-right">
                          <div className="flex justify-end gap-2">
                            <Button
                              variant="ghost"
                              size="sm"
                              onClick={() => onEdit && onEdit(tower)}
                            >
                              <Edit className="w-4 h-4" />
                            </Button>
                            <Button
                              variant="ghost"
                              size="sm"
                              onClick={() => onDelete && onDelete(tower.id)}
                              className="text-red-600 hover:text-red-700"
                            >
                              <Trash2 className="w-4 h-4" />
                            </Button>
                          </div>
                        </TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              </div>
              {renderPagination()}
            </>
          ) : (
            <div className="text-center py-12 border-2 border-dashed border-gray-200 rounded-lg">
              <Pilcrow className="w-16 h-16 text-gray-300 mx-auto mb-4" />
              <p className="text-gray-500 mb-2">该项目下暂无杆塔</p>
              <p className="text-sm text-gray-400 mb-4">请添加杆塔以继续</p>
              <Button onClick={onAddNew}>
                <Plus className="w-4 h-4 mr-2" />
                新增第一个杆塔
              </Button>
            </div>
          )}
        </CardContent>
      </Card>
      
      {/* 批量导入模态框 */}
      {isImportModalOpen && (
        <PronJectModal
          isOpen={isImportModalOpen}
          onClose={() => setIsImportModalOpen(false)}
          projectId={project.id}
          onImportSuccess={handleImportSuccess}
          // 传递数值限制配置
          numberFormatConfig={{
            maxDecimals: 2,
            allowNegative: false
          }}
          // 传递现有杆塔数据用于重复检测
          existingTowers={projectTowers}
        />
      )}
    </>
  );
}

// 编辑杆塔的模态框组件（示例）
const TowerEditModal = ({ tower, onSave, onCancel }) => {
  const [formData, setFormData] = useState({
    height: tower?.height || "",
    groundElevation: tower?.groundElevation || "",
    spanToNextTower: tower?.spanToNextTower || "",
    latitude: tower?.latitude || "",
    longitude: tower?.longitude || "",
    // ... 其他字段
  });

  const handleNumberChange = (field, value) => {
    handleNumberInput(value, (newValue) => {
      setFormData(prev => ({
        ...prev,
        [field]: newValue
      }));
    });
  };

  const handleBlur = (field) => {
    const value = formData[field];
    if (value === "") return;
    
    const numValue = parseFloat(value);
    if (!isNaN(numValue)) {
      // 限制为两位小数
      const formattedValue = parseFloat(numValue.toFixed(2));
      setFormData(prev => ({
        ...prev,
        [field]: formattedValue.toString()
      }));
    }
  };

  return (
    <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
      <div className="bg-white rounded-lg p-6 w-full max-w-md">
        <h3 className="text-lg font-semibold mb-4">
          {tower ? "编辑杆塔" : "新增杆塔"}
        </h3>
        
        <div className="space-y-4">
          <div>
            <label className="block text-sm font-medium mb-1">高度 (m)</label>
            <NumberInput
              value={formData.height}
              onChange={(value) => handleNumberChange("height", value)}
              placeholder="请输入高度"
              min="0"
            />
            <p className="text-xs text-gray-500 mt-1">最多两位小数</p>
          </div>
          
          <div>
            <label className="block text-sm font-medium mb-1">呼称高 (m)</label>
            <NumberInput
              value={formData.groundElevation}
              onChange={(value) => handleNumberChange("groundElevation", value)}
              placeholder="请输入呼称高"
              min="0"
            />
            <p className="text-xs text-gray-500 mt-1">最多两位小数</p>
          </div>
          
          <div>
            <label className="block text-sm font-medium mb-1">到下一塔档距 (m)</label>
            <NumberInput
              value={formData.spanToNextTower}
              onChange={(value) => handleNumberChange("spanToNextTower", value)}
              placeholder="请输入档距"
              min="0"
            />
            <p className="text-xs text-gray-500 mt-1">最多两位小数</p>
          </div>
          
          <div className="grid grid-cols-2 gap-4">
            <div>
              <label className="block text-sm font-medium mb-1">纬度</label>
              <NumberInput
                value={formData.latitude}
                onChange={(value) => handleNumberChange("latitude", value)}
                placeholder="纬度"
              />
            </div>
            <div>
              <label className="block text-sm font-medium mb-1">经度</label>
              <NumberInput
                value={formData.longitude}
                onChange={(value) => handleNumberChange("longitude", value)}
                placeholder="经度"
              />
            </div>
          </div>
          
          <p className="text-xs text-gray-500">坐标值最多支持6位小数精度</p>
        </div>
        
        <div className="flex justify-end gap-2 mt-6">
          <Button variant="outline" onClick={onCancel}>
            取消
          </Button>
          <Button onClick={() => onSave(formData)}>
            保存
          </Button>
        </div>
      </div>
    </div>
  );
};

export { TowerEditModal, NumberInput, formatNumber, handleNumberInput };